package edu.yuhf.web.filter;

import lombok.extern.log4j.Log4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Log4j
//@WebFilter(urlPatterns = "/api/*", filterName = "crossDomainFilter")
public class CrossDomainFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("CrossDomainFilter");

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

        response.setHeader("Access-Control-Allow-Method", "*");

        response.setHeader("Access-Control-Max-Age", "3600");


        /*
         *  响应首部 Access-Control-Allow-Headers 用于 preflight request （预检请求）中
         *  列出了将会在正式请求的 Access-Control-Request-Headers 字段中出现的首部信息
         *
         *  注意以下这些特定的首部是一直允许的：
         *  	Accept, Accept-Language, Content-Language,Content-Type
         *  	其中 Content-Type （只在其值属于 MIME 类型 application/x-www-form-urlencoded, multipart/form-data 或
         *  	text/plain中的一种）。
         *  	这些被称作simple headers，你无需特意声明它们。
         */
        // response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        //response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");
        //Origin, X-Requested-With, Content-Type, Accept,Access-Token

        /*
         * 响应首部 Access-Control-Expose-Headers 列出了哪些首部可以作为响应的一部分暴露给外部
         *
         * 默认情况下，只有六种 simple response headers （简单响应首部）可以暴露给外部：
         * Cache-Control
         * Content-Language
         * Content-Type
         * Expires
         * Last-Modified
         * Pragma
         * 如果想要让客户端可以访问到其他的首部信息，可以将它们在 Access-Control-Expose-Headers 里面列出来
         */
        //response.setHeader("Access-Control-Expose-Headers", "checkTokenResult");
        //设置可以暴露在外的响应头
        //response.setHeader("Access-Control-Expose-Headers", "message");


        /*
         * 允许cookie跨域
         * */
        // 指示的请求的响应是否可以暴露于该页面。当返回true时他可以被暴露Credentials
        //response.setHeader("Access-Control-Allow-Credentials", "true");

        /*Credentials
         * no-cache：
         * 	在发布缓存副本之前，强制要求缓存把请求提交给原始服务器进行验证。
         */
        //response.setHeader("Cache-Control", "no-cache");

        // 把请求传回过滤链
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
